﻿using SoldiHive.Core.Persistence;
using SoldiHive.Infrustructure.Extensions;
using SoldiHive.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SoldiHive.Core.Crawlers
{
	public class QuotesCrawler : IQuotesCrawler
	{
		private ICompanyRepository companyRepository;
		private IQuoteRepository quotesRepository;

		public QuotesCrawler(ICompanyRepository companyRepository, IQuoteRepository quotesRepository)
		{
			this.companyRepository = companyRepository;
			this.quotesRepository = quotesRepository;
		}

		public Quote GetQuote(Company company, DateTime date)
		{
			var quote = this.quotesRepository.GetQuote(company, date, true);

			return quote;
		}

		public IList<Quote> GetNeighbouringQuotes(Company company, DateTime date)
		{
			const int businessDatesBeforeCount = 2;
			const int businessDatesAfterCount = businessDatesBeforeCount;

			return this.GetNeighbouringQuotes(company, date, businessDatesBeforeCount, businessDatesAfterCount);
		}

		public IList<Quote> GetNeighbouringQuotes(Company company, DateTime date, int neighbouringDaysCount)
		{
			return this.GetNeighbouringQuotes(company, date, neighbouringDaysCount, neighbouringDaysCount);
		}

		public IList<Quote> GetNeighbouringQuotes(Company company, DateTime date, int beforeCount, int afterCount)
		{
			var neighbouringBusinessDates = date.GetNeighbouringBusinessDates(beforeCount, afterCount);
			var neighbouringQuotes = neighbouringBusinessDates
				.Select(neighbouringBusinessDate => this.GetQuote(company, neighbouringBusinessDate))
				.Where(quote => quote != null)
				.ToList();

			return neighbouringQuotes;
		}
	}
}
